package com.tencent.crazypenguin.action;

import java.io.IOException;
import java.sql.Timestamp;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.opensymphony.xwork2.ActionSupport;
import com.tencent.crazypenguin.bean.User;
import com.tencent.crazypenguin.config.HbmUtil;
import com.tencent.crazypenguin.config.ResultType;
import com.tencent.crazypenguin.util.JsonUtil;

import net.sf.json.JSONObject;

public class Comments extends ActionSupport {
	/**
	 * by zhm
	 */
	private static final long serialVersionUID = -1660704502356077315L;

	public String execute() throws Exception {

		// 获取输入数据
		JSONObject postJson = JsonUtil.getPostData();
		String loginName = postJson.getString("loginName");
		String comment = postJson.getString("comments");
	    
//		//test01--
//		String loginName = "user4";
//		String comment = "19";
//		//--test01

		// 插入评分数据
		Session s = HbmUtil.getSession();

		try {

			Transaction trans = s.beginTransaction();
			String loginID = Long.toString(getUserID(loginName));
			Timestamp timeGo = getTimeGo(loginName);
			
//			//test02--
//			String loginID = Long.toString(getUserID("user4"));
//			Timestamp timeGo = getTimeGO("user4");
//			//--test02
			
			String hqlUpdate = "UPDATE Comments SET star_com = " + comment 
			         + "WHERE id_docom=" + loginID + "AND time_go = '" + timeGo +"'";   //注：字段date类型，少了''不行。

			s.createQuery(hqlUpdate).executeUpdate();
			trans.commit();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "done";
	}

	@SuppressWarnings("rawtypes")
	public long getUserID(String loginName) {

		long loginID = 0;
		Session s = HbmUtil.getSession();
		s.beginTransaction();

//		//test03--
//		Query query = s.createQuery("select id from User where user = 'user4'");
//		//--test03
		
		Query query = s.createQuery("SELECT id FROM test_user WHERE user = ?");
		query.setParameter(0, loginName);
		
		loginID = (long)query.getSingleResult();
		s.getTransaction().commit();
		s.close();

		return loginID;
	}
	
	@SuppressWarnings("rawtypes")
	public Timestamp getTimeGo(String loginName) {

		Timestamp timeGo = null;
		Session s = HbmUtil.getSession();
		s.beginTransaction();

//		//test03--
//		Query query = s.createQuery("select p_time from User where user = 'user4'");
//		//--test03
		
		Query query = s.createQuery("SELECT p_time FROM User WHERE user = ?");
		query.setParameter(0, loginName);
		
		timeGo = (Timestamp)query.getSingleResult();
		s.getTransaction().commit();
		s.close();
		return timeGo;
	}

}
